package com.datareport.data.security;

import cn.hutool.json.JSONUtil;
import com.datareport.data.dto.ResultDTO;
import com.datareport.data.exception.CustomizeErrorCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限不足处理类
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
      @ExceptionHandler(AccessDeniedException.class)
      @Override
      public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
              throws IOException,ServletException {

         response.setContentType("application/json;charset=UTF-8");
         response.setStatus(HttpServletResponse.SC_FORBIDDEN);

         ServletOutputStream outputStream = response.getOutputStream();

         ResultDTO result = ResultDTO.errorOf(CustomizeErrorCode.INSUFFICIENT_PERMISSIONS);

         outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

         outputStream.flush();
         outputStream.close();

      }
   }